import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/login'
// import Register from '@/views/register'
import { getItem } from '@/utils/storage'
// import Detail from '@/views/detail'
import Layout from '@/views/layout'
// import Article from '@/views/article'
// import Collect from '@/views/collect'
// import Like from '@/views/like'
// import User from '@/views/user'
// 路由懒加载
const Detail = () => import('@/views/detail')
const Register = () => import('@/views/register')
const Login = () => import('@/views/login')
const Article = () => import('@/views/article')
const Collect = () => import('@/views/collect')
const Like = () => import('@/views/like')
const User = () => import('@/views/user')
Vue.use(VueRouter)
// 二级路由的出口要放在他父级组件上(layout.vue)
const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/detail/:id', component: Detail },
  {
    path: '/',
    redirect: '/article',
    component: Layout,
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局路由守卫
// 1. 所有的路由一旦被匹配到,,在渲染之前,都会先经过全局前置路由守卫
// 2. 只有全局路由守卫放行了,才能看到页面

const whiteList = ['/login', '/register']
// 任何路由,被解析访问前,都会先执行这个回调
// 1. from  从哪来   路由信息对象
// 2. to   到哪去    路由信息对象
// 3. next  函数  决定是否放行  next()   next(路径)
router.beforeEach((to, from, next) => {
  // console.log(to)
  // console.log(from)
  // console.log(next)
  // 有token放行, 没token去登录 定义个白名单,在白名单里的不用登录
  const token = getItem()
  if (token) {
    next()
  } else {
    // 没token去的是白名单里有的页面  放行
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 否则拦截到登录页
      next('/login')
    }
  }
})

export default router
